<template>
  <wd-popup
    v-model="loadVisible"
    @close="onClose"
    position="center"
    custom-style="width: 43vw;height: 37vh;"
    custom-class="p-[32px] rounded pd-[0px] box-border"
  >
    <view class="datetime-wrapper-content">
      <view class="mb-[16px] font-600 text-[22px]" v-if="title">{{ title }}</view>
      <view>
        <wd-datetime-picker-view v-model="defaultValue" label="日期选择" :formatter="formatter" />
      </view>

      <view class="text-right">
        <wd-button type="text" class="mr-[20px]" @click="onClose">取消</wd-button>
        <wd-button type="text" @click="onSubimt">确定</wd-button>
      </view>
    </view>
  </wd-popup>
</template>

<script lang="ts" setup>
import { computed, watch } from 'vue'
import { formatToDateTime, getMilliTimestamp } from '@/utils/dateUtil'
import { isArray } from '@/utils/index'

const formatter = (type, value) => {
  switch (type) {
    case 'year':
      return value + '年'
    case 'month':
      return value + '月'
    case 'date':
      return value + '日'
    case 'hour':
      return value + '时'
    case 'minute':
      return value + '分'
    default:
      return value
  }
}

interface Props {
  visible: boolean
  title?: string
  value: string | Date | undefined
  valueType?: 'yyyy-MM-dd HH:mm' | 'Unix'
}

const props = withDefaults(defineProps<Props>(), {
  valueType: 'yyyy-MM-dd HH:mm',
})

const emit = defineEmits<{
  'update:visible': [value: boolean]
  'update:value': [value: any]
}>()

const defaultValue = ref<Date | number>(initStartDate())

const loadVisible = computed({
  get: () => {
    return props.visible
  },

  set: (val) => {
    emit('update:visible', val)
  },
})

watch(
  () => props.visible,
  (newValue) => {
    if (!newValue) return

    if (props.value === undefined) {
      defaultValue.value = initStartDate()
    } else if (isArray(props.value) && props.value) {
      const _defaultValue = formatToDateTime(new Date(props.value[0]), 'yyyy-MM-dd HH:mm')
      defaultValue.value = getMilliTimestamp(new Date(_defaultValue))
    }
  },
)

function initStartDate() {
  const currentTime = new Date()

  return currentTime.setSeconds(0)
}

const onClose = () => {
  loadVisible.value = false
  defaultValue.value = initStartDate()
}

const onSubimt = () => {
  loadVisible.value = false
  let params

  if (props.valueType === 'Unix') {
    params = getMilliTimestamp(defaultValue.value)
  } else {
    params = formatToDateTime(defaultValue.value, 'yyyy-MM-dd HH:mm:ss')
  }

  emit('update:value', params)
}
</script>

<style lang="scss" scoped>
.datetime-wrapper-content {
  width: 100%;
  min-height: 20%;
  background-color: #fff;
  border-radius: 8px;

  display: flex;
  flex-direction: column;
}
</style>
